package request

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"

	"cmt1-admin/conf"
)

func Post(api string, data interface{}) (r []byte, err error) {
	b, err := json.Marshal(data)
	if err != nil {
		return
	}
	body := bytes.NewReader(b)
	res, err := http.Post(conf.Conf.GameHttp+"/"+api, "application/json", body)
	if err != nil {
		return
	}
	defer res.Body.Close()
	r, _ = ioutil.ReadAll(res.Body)
	return
}

func PostByte(api string, b []byte) (r []byte, err error) {
	body := bytes.NewReader(b)
	res, err := http.Post(conf.Conf.GameHttp+"/"+api, "application/json", body)
	if err != nil {
		return
	}
	defer res.Body.Close()
	r, _ = ioutil.ReadAll(res.Body)
	return
}

func Get(api string) (r []byte, err error) {
	res, err := http.Get(conf.Conf.GameHttp + "/" + api)
	if err != nil {
		return
	}
	defer res.Body.Close()
	r, _ = ioutil.ReadAll(res.Body)
	return
}

func SAGet(ip, port, api string) (r []byte, err error) {
	res, err := http.Get("http://" + ip + ":" + port + "/" + api)
	if err != nil {
		return
	}
	defer res.Body.Close()
	r, _ = ioutil.ReadAll(res.Body)
	return
}

func SAPost(ip, port, api string, data interface{}) (r []byte, err error) {
	b, err := json.Marshal(data)
	if err != nil {
		return
	}
	body := bytes.NewReader(b)
	res, err := http.Post("http://"+ip+":"+port+"/"+api, "application/json", body)
	if err != nil {
		return
	}
	defer res.Body.Close()
	r, _ = ioutil.ReadAll(res.Body)
	return
}
